﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SchedulerJob.job;
using Hangfire;
using KJFrame.Core.Job;
using KJFrame.Core.Job.Config;
using KJFrame.Core.Job.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace SchedulerJob
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(x => x.UseSqlServerStorage("server=192.168.1.109;database=Hangfire;User ID=sa;Password=198603yang;"));

            //services.AddHangfire(x => x.UseRedisStorage("redis 连接地址"));

            //注册IRepeatJob的实现类
            services.AddSingleton<IRepeatJob, OrderJob>();

            //注册IRepeatJob的配置
            services.Configure<JobConfigs>(Configuration.GetSection("JobConfigs"));
         
        }

        /// <summary>
        /// 注册管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region 
            // 配置 登陆
            //var filter = new BasicAuthAuthorizationFilter(
            //new BasicAuthAuthorizationFilterOptions
            //{
            //    SslRedirect = false,          // 是否将所有非SSL请求重定向到SSL URL
            //    RequireSsl = false,           // 需要SSL连接才能访问HangFire Dahsboard。强烈建议在使用基本身份验证时使用SSL
            //    LoginCaseSensitive = false,   //登录检查是否区分大小写
            //    Users = new[]
            //    {
            //      new BasicAuthAuthorizationUser
            //       {
            //        Login ="hangfire",//用户名
            //        PasswordClear="111"
            //         // Password as SHA1 hash
            //          //Password=new byte[]{ 0xf3,0xfa，，0xd1 }
            //        }
            //    }
            //});
            //var optionsDashboard = new DashboardOptions
            //{
            //    //Authorization = new[] { new HangfireDashboardAuthorizationFilter() }

            //    //AuthorizationFilters = new[]
            //    //{
            //    //    filter
            //    //}

            //};
            //app.UseHangfireDashboard("/hf", optionsDashboard);//启动hangfire面板 
            #endregion

            //配置作业队列
            var options = new BackgroundJobServerOptions
            {
                // 队列名称，只能为小写
                Queues = new[] { "a", "default" },
                
                //并发任务数
                WorkerCount = Environment.ProcessorCount * 5,
                
                //服务器名称
                ServerName = "hangfire1",

                //未设置轮询间隔Hangfire默认是15秒轮询间隔
                SchedulePollingInterval = TimeSpan.FromSeconds(30),
            };

            //启动hangfire服务并在数据库中创建表
            app.UseHangfireServer(options);

            //扫描所有IRepeatJob的实现类的作业
            app.UseJob(Configuration);

            //启动hangfire面板
            app.UseHangfireDashboard();

            app.Run(async (context) =>
            {
                //如果您不想使用KJFrame.Core.Job来实现重复作业，或者您的作业不多，较简单时，可以参考此实例
                RecurringJob.AddOrUpdate(() => SampleJob(), "*/50 * * * * ?");
            });
        }

        public void SampleJob()
        {
            Console.WriteLine(DateTime.Now);
        }

    }
}
